#include "cgi_interface.h"
#include "sql.h"
#include "cJSON.h"

char *sql_table[]={"ZB_Bedroom", "ZB_Livingroom", "ZB_Kitchen", "ZB_Bathroom"};

char *sensor_table[]  = {NULL, NULL, "Psst_Table", NULL, NULL, NULL, "Light_Table", "Temperature_Table", "Humidity_Table", "Door_Table", "Fan_Table", "Beep_Table", "Smoke_Table", "Calorifier_Table", "Curtain_Table"};
char *devcfg_table    = "DeviceCfg";//设备配置表

/*********************************************************************
 * @fn      CGI_Logic_Judge
 *
 * @brief   登陆判断函数
 *
 * @param   user_name:用户名  user_passwd:密码
 *
 * @return  正确返回0 错误返回-1
 */
int CGI_Logic_Judge(char *user_name, char *user_passwd)
{
	int res=-1;

	Sem_Init();
	Msg_queue_Init();

	res = sql_logic_table_judge("user", user_name, user_passwd);

	return res;
}

/*********************************************************************
 * @fn      CGI_LED_Control
 *
 * @brief   节点LED控制函数
 *
 * @param   room_id:房间ID  led_id:灯光ID  led_status:灯光状态
 *
 * @return  成功返回0 失败返回-1
 */
int CGI_Led_Control(const char *dev_mac, const unsigned int led_id, const unsigned char led_status)
{
	int res=0;
	Light_Ctrl_pkg light_pkg;
	uartmsg uart_msg;
	char dev_str_mac[32];

	Sem_Init();
	Msg_queue_Init();

	//将mac地址转成字符串
	mac_transition_str(dev_str_mac, dev_mac);

	memcpy(light_pkg.mac, dev_str_mac, 8);


	light_pkg.which    = led_id;
	light_pkg.status   = led_status;

	uart_msg.msgtype   = MSG_QUEUE_ZB_TYPE;//消息类型
	uart_msg.count     = sizeof(Light_Ctrl_pkg);
	uart_msg.cmd       = CMD_LIGHT;

	memcpy((void *)uart_msg.data, (void *)&light_pkg, sizeof(Light_Ctrl_pkg));
	poperation(sem_msg_queue_qt_id, g_sem_id);//消息队列读写锁
	res = msgsnd(g_msgid, (void *)&uart_msg, sizeof(uartmsg)-sizeof(long), 0);
	voperation(sem_msg_queue_qt_id, g_sem_id);


	return res;
}

int CGI_Led_Control_RE(const char *dev_mac, const unsigned char led_status)
{
    int res;

    res = CGI_Led_Control(dev_mac, 0, led_status);

    return res;
}

/*********************************************************************
 * @fn      CGI_Get_Led_Status
 *
 * @brief   节点Led状态获取
 *
 * @param   room_id:房间ID  led_id:灯光ID  led_status:灯光状态(传出参数)
 *
 * @return  节点Led状态 错误返回-1
 */
int CGI_Get_Led_Status(const char *dev_mac, const unsigned int led_id)
{
	int res=0;

	//mac_transition_str(dev_str_mac, dev_mac);

	Sem_Init();
	Msg_queue_Init();

	//查询数据库中的值
	res = sql_query_intfield_by_strfield(sensor_table[CMD_LIGHT], "sensor_status", "dev_mac", dev_mac);

	return res;
}

/*********************************************************************
 * @fn      CGI_Get_Temperature
 *
 * @brief   节点温度获取
 *
 * @param   none
 *
 * @return  节点温度数据 错误返回-1
 */
int CGI_Get_Temperature(const char *dev_mac)
{
	int res=0;

	//mac_transition_str(dev_str_mac, dev_mac);

	Sem_Init();
	Msg_queue_Init();

	//查询数据库中的值
	res = sql_query_intfield_by_strfield(sensor_table[CMD_TEMPERATURE], "sensor_status", "dev_mac", dev_mac);

	return res;
}

/*********************************************************************
 * @fn      CGI_Get_Humidity
 *
 * @brief   节点湿度
 *
 * @param   none
 *
 * @return  节点湿度数据 错误返回-1
 */
int CGI_Get_Humidity(const char *dev_mac)
{
	int res=0;

	//mac_transition_str(dev_str_mac, dev_mac);

	Sem_Init();
	Msg_queue_Init();

	//查询数据库中的值
	res = sql_query_intfield_by_strfield(sensor_table[CMD_HUMIDITY], "sensor_status", "dev_mac", dev_mac);

	return res;
}

/*********************************************************************
 * @fn      CGI_Get_Light_Intensity
 *
 * @brief   节点光强
 *
 * @param   room_id:房间id
 *
 * @return  节点光照强度数据 错误返回-1
 */
int CGI_Get_Light_Intensity(const char *dev_mac)
{
	int res=0;

	//mac_transition_str(dev_str_mac, dev_mac);

	Sem_Init();
	Msg_queue_Init();

	//查询数据库中的值
	res = sql_query_intfield_by_strfield(sensor_table[CMD_PSST], "sensor_status", "dev_mac", dev_mac);

	return res;
}

/*********************************************************************
 * @fn      CGI_Door_Control
 *
 * @brief   门状态设置
 *
 * @param   door_status:门状态
 *
 * @return  成功返回0 失败返回-1
 */
int CGI_Door_Control(const char *dev_mac, const unsigned char door_status)
{
	int res=0;
	Door_pkg door_pkg;
	uartmsg uart_msg;
	char dev_str_mac[32];

	Sem_Init();
	Msg_queue_Init();

	//将mac地址转成字符串
	mac_transition_str(dev_str_mac, dev_mac);
	memcpy(door_pkg.mac, dev_str_mac, 8);
	door_pkg.status    = door_status;

	uart_msg.msgtype   = MSG_QUEUE_ZB_TYPE;//消息类型
	uart_msg.count     = sizeof(Door_pkg);
	uart_msg.cmd       = CMD_DOOR;
	memcpy((void *)uart_msg.data, (void *)&door_pkg, sizeof(Door_pkg));
	poperation(sem_msg_queue_qt_id, g_sem_id);//消息队列读写锁
	res = msgsnd(g_msgid, (void *)&uart_msg, sizeof(uartmsg)-sizeof(long), 0);
	voperation(sem_msg_queue_qt_id, g_sem_id);

	return res;
}

/*********************************************************************
 * @fn      CGI_Get_Door_Status
 *
 * @brief   门状态获取
 *
 * @param   none
 *
 * @return  成功返回门当前状态 失败返回-1
 */
int CGI_Get_Door_Status(const char *dev_mac)
{
	int res=0;

	//mac_transition_str(dev_str_mac, dev_mac);

	Sem_Init();
	Msg_queue_Init();

	//查询数据库中的值
	res = sql_query_intfield_by_strfield(sensor_table[CMD_DOOR], "sensor_status", "dev_mac", dev_mac);

	return res;
}

/*********************************************************************
 * @fn      CGI_Get_Smoke_Status
 *
 * @brief   MQ_2状态获取
 *
 * @param   none
 *
 * @return  成功返回烟雾传感器当前状态 失败返回-1
 */
int CGI_Get_Smoke_Status(const char *dev_mac)
{
	int res=0;

	//mac_transition_str(dev_str_mac, dev_mac);

	Sem_Init();
	Msg_queue_Init();

	//查询数据库中的值
	res = sql_query_intfield_by_strfield(sensor_table[CMD_SMOKE], "sensor_status", "dev_mac", dev_mac);

	return res;
}

/*********************************************************************
 * @fn      CGI_Beep_Control
 *
 * @brief   Beep状态控制
 *
 * @param   none
 *
 * @return  成功返回0 失败返回-1
 *
 */
int CGI_Beep_Control(const char *dev_mac, const unsigned char beep_status)
{
	int res=0;
	Beep_pkg beep_pkg;
	uartmsg uart_msg;
	char dev_str_mac[32];

	Sem_Init();
	Msg_queue_Init();

	//将mac地址转成字符串
	mac_transition_str(dev_str_mac, dev_mac);
	memcpy(beep_pkg.mac, dev_str_mac, 8);
	beep_pkg.status    = beep_status;

	uart_msg.msgtype   = MSG_QUEUE_ZB_TYPE;//消息类型
	uart_msg.count     = sizeof(beep_pkg);
	uart_msg.cmd       = CMD_BEEP;
	memcpy((void *)uart_msg.data, (void *)&beep_pkg, sizeof(Beep_pkg));
	poperation(sem_msg_queue_qt_id, g_sem_id);//消息队列读写锁
	res = msgsnd(g_msgid, (void *)&uart_msg, sizeof(uartmsg)-sizeof(long), 0);
	voperation(sem_msg_queue_qt_id, g_sem_id);

	return res;
}

/*********************************************************************
 * @fn      CGI_Get_Beep_Status
 *
 * @brief   Beep状态获取
 *
 * @param   none
 *
 * @return  成功返回Beep状态 失败返回-1
 *
 */
int CGI_Get_Beep_Status(const char *dev_mac)
{
	int res=0;

	//mac_transition_str(dev_str_mac, dev_mac);

	Sem_Init();
	Msg_queue_Init();

	//查询数据库中的值
	res = sql_query_intfield_by_strfield(sensor_table[CMD_BEEP], "sensor_status", "dev_mac", dev_mac);

	return res;
}

/*********************************************************************
 * @fn      CGI_Fan_Control
 *
 * @brief   Fan状态设置
 *
 * @param   none
 *
 * @return  成功返回0 失败返回-1
 *
 */
int CGI_Fan_Control(const char *dev_mac, const unsigned char fan_status)
{
	int res=0;
	Fan_pkg fan_pkg;
	uartmsg uart_msg;
	char dev_str_mac[32];

	Sem_Init();
	Msg_queue_Init();

	//将mac地址转成字符串
	mac_transition_str(dev_str_mac, dev_mac);
	memcpy(fan_pkg.mac, dev_str_mac, 8);
	fan_pkg.status   = fan_status;

	uart_msg.msgtype = MSG_QUEUE_ZB_TYPE;//消息类型
	uart_msg.count   = sizeof(Fan_pkg);
	uart_msg.cmd     = CMD_RELAY;
	memcpy((void *)uart_msg.data, (void *)&fan_pkg, sizeof(Fan_pkg));
	poperation(sem_msg_queue_qt_id, g_sem_id);//消息队列读写锁
	res = msgsnd(g_msgid, (void *)&uart_msg, sizeof(uartmsg)-sizeof(long), 0);
	voperation(sem_msg_queue_qt_id, g_sem_id);

	return res;
}

/*********************************************************************
 * @fn      CGI_Get_Fan_Status
 *
 * @brief  	fan状态获取
 *
 * @param   none
 *
 * @return  成功返回Fan状态 失败返回-1
 *
 */
int CGI_Get_Fan_Status(const char *dev_mac)
{
	int res=0;

	//mac_transition_str(dev_str_mac, dev_mac);

	Sem_Init();
	Msg_queue_Init();

	//查询数据库中的值
	res = sql_query_intfield_by_strfield(sensor_table[CMD_RELAY], "sensor_status", "dev_mac", dev_mac);

	return res;
}

/*********************************************************************
 * @fn      CGI_Calorifier_Control
 *
 * @brief   calorifier状态设置
 *
 * @param   none
 *
 * @return  成功返回0 失败返回-1
 *
 */
int CGI_Calorifier_Control(const char *dev_mac, const unsigned char calorifier_status)
{
	int res=0;
	Calorifier_pkg calorifier_pkg;
	uartmsg uart_msg;
	char dev_str_mac[32];

	Sem_Init();
	Msg_queue_Init();

	//将mac地址转成字符串
	mac_transition_str(dev_str_mac, dev_mac);
	memcpy(calorifier_pkg.mac, dev_str_mac, 8);
	calorifier_pkg.status   = calorifier_status;

	uart_msg.msgtype        = MSG_QUEUE_ZB_TYPE;//消息类型
	uart_msg.count          = sizeof(Calorifier_pkg);
	uart_msg.cmd            = CMD_CALORIFIER;
	memcpy((void *)uart_msg.data, (void *)&calorifier_pkg, sizeof(Calorifier_pkg));
	poperation(sem_msg_queue_qt_id, g_sem_id);//消息队列读写锁
	res = msgsnd(g_msgid, (void *)&uart_msg, sizeof(uartmsg)-sizeof(long), 0);
	voperation(sem_msg_queue_qt_id, g_sem_id);

	return res;
}

/*********************************************************************
 * @fn      CGI_Get_Calorifier_Status
 *
 * @brief   Calorifier状态获取
 *
 * @param   none
 *
 * @return  成功返回Calorifier状态 失败返回-1
 *
 */
int CGI_Get_Calorifier_Status(const char *dev_mac)
{
	int res=0;

	//mac_transition_str(dev_str_mac, dev_mac);

	Sem_Init();
	Msg_queue_Init();

	//查询数据库中的值
	res = sql_query_intfield_by_strfield(sensor_table[CMD_CALORIFIER], "sensor_status", "dev_mac", dev_mac);

	return res;
}

/*********************************************************************
 * @fn      CGI_Curtain_Control
 *
 * @brief   状态设置
 *
 * @param   none
 *
 * @return  成功返回0 失败返回-1
 *
 */
int CGI_Curtain_Control(const char *dev_mac, const unsigned char curtain_status)
{
	int res=0;
	Curtain_pkg curtain_pkg;
	uartmsg uart_msg;
	char dev_str_mac[32];

	Sem_Init();
	Msg_queue_Init();

	//将mac地址转成字符串
	mac_transition_str(dev_str_mac, dev_mac);
	memcpy(curtain_pkg.mac, dev_str_mac, 8);
	curtain_pkg.status   = curtain_status;

	uart_msg.msgtype     = MSG_QUEUE_ZB_TYPE;//消息类型
	uart_msg.count       = sizeof(Curtain_pkg);
	uart_msg.cmd         = CMD_CURTAIN;
	memcpy((void *)uart_msg.data, (void *)&curtain_pkg, sizeof(Curtain_pkg));
	poperation(sem_msg_queue_qt_id, g_sem_id);//消息队列读写锁
	res = msgsnd(g_msgid, (void *)&uart_msg, sizeof(uartmsg)-sizeof(long), 0);
	voperation(sem_msg_queue_qt_id, g_sem_id);

	return res;
}

/*********************************************************************
 * @fn      CGI_Get_Curtain_Status
 *
 * @brief   Curtain状态获取
 *
 * @param   none
 *
 * @return  成功返回Curtain状态 失败返回-1
 *
 */
int CGI_Get_Curtain_Status(const char *dev_mac)
{
	int res=0;

	//mac_transition_str(dev_str_mac, dev_mac);

	Sem_Init();
	Msg_queue_Init();

	//查询数据库中的值
	res = sql_query_intfield_by_strfield(sensor_table[CMD_CURTAIN], "sensor_status", "dev_mac", dev_mac);

	return res;
}

/*********************************************************************
 * @fn      CGI_Get_Online_DEV_Count
 *
 * @brief   在线设备数量
 *
 * @param   none
 *
 * @return  成功返回在线设备数量 失败返回-1
 *
 */
int CGI_Get_Online_DEV_Count(void)
{
	int res=0,i,count=0;
	int buf[32][2];
	int col[]={0,4};

	res = sql_get_table_msg_int("DeviceCfg", col, 2, buf);

	if(res!=-1)
	{
		for(i=0; i<res; ++i)
		{
			if(buf[i][1]==ZB_DEV_ONLINE)
			{
				count++;
			}
		}

		res = count;
	}

	return res;
}

/*********************************************************************
 * @fn      Update_Dev_List
 *
 * @brief   在线设备数量
 *
 * @param   none
 *
 * @return  成功返回0 失败返回-1
 *
 */
 int Update_Dev_List(void)
 {
	 voperation(sem_send_dev_online_list, g_sem_id);//更新设备列表
	 return 0;
 }

 /*********************************************************************
 * @fn      Update_Dev_List_cfg
 *
 * @brief   返回设备的配置信息表
 *
 * @param   none
 *
 * @return  成功返回0 失败返回-1
 *
 */
 int Update_Dev_List_cfg(void)
 {
	Sem_Init();
	Msg_queue_Init();
	voperation(sem_send_dev_cfg_list, g_sem_id);//更新设备配置信息列表
	return 0;
 }

/*********************************************************************
* @fn      Set_Dev_Cfg
*
* @brief   设置某个设备的设备名和设备使用区域
*
* @param   table_name:表名
* @param   field_str:字段值数组(dev_mac dev_name dev_region)
* @param   n:字段数组的长度
*
* @return  成功返回0 失败返回-1
*
*/
int Set_Dev_Cfg(const char *table_name, char field_str[][1024], int n)
{
	int i,res=0;
	char *dev_table_list[]={"dev_mac", "dev_name", "dev_region", };

	for(i=1; i<n; ++i)
	{
		res = update_field_value_by_str(table_name, dev_table_list[0], field_str[0], dev_table_list[i], field_str[i]);
		if(res==-1)
		{
			break;
		}
	}

	return res;
}

/*********************************************************************
* @fn      Set_Sensor_Cfg
*
* @brief   设置对应设备的传感器name
*
* @param   type:传感器类型(CMD_LIGHT CMD_DOOR)
* @param   field_str:字段值数组(dev_mac sensor_name)
*
* @return  成功返回0 失败返回-1
*
*/
int Set_Sensor_Cfg(const char type, char field_str[][1024], int n)
{
	int i,res=0;
	char *sensor_list[]={"dev_mac", "sensor_name"};

	for(i=1; i<n; ++i)
	{
		res = update_field_value_by_str(sensor_table[type], sensor_list[0], field_str[0], sensor_list[i], field_str[i]);
		if(res==-1)
		{
			break;
		}
	}

	return res;
}

/*********************************************************************
* @fn      Get_Sensor_info
*
* @brief   获取传感器表的信息和区域范围
*
* @param   type:复合字段，每一个位表示一个传感器类型
* @param   result_str:存放结果的数组
*
* @return  成功返回0 失败返回-1
*
*/
int Get_Sensor_info(int type, char *result_str)
{
	//{{"dev_mac":"", "dev_status":TRUE, "dev_region":"", "sensor_name":"", "sensor_status":TRUE},}
	//dev_mac sensor_name sensor_status

	int i,j,k,res=0,ret;
	int dat_result;
	char *result;
	char sensor_dat[10][10][256];
	char dev_dat[128];
	int col[]={0,1,2};
	char *json_root_name = "type_list";
	char *item_field_name[]={"dev_mac", "sensor_name", "sensor_status", "dev_region", "dev_status", "sensor_type"};
	char col_type[]={SQL_FIEL_TYPE_STR, SQL_FIEL_TYPE_STR, SQL_FIEL_TYPE_INT};
	cJSON *js_root,*js_sensor_arry,*js_item;

	js_root             = cJSON_CreateObject();
	js_sensor_arry      = cJSON_CreateArray();
	for(i=0; i<32; ++i)
	{
		if(type & (1<<i))
		{
			ret = sql_get_table_nfield(sensor_table[i], col, col_type, 3, sensor_dat);
			//printf("ret = %d\n", ret);
			for(j=0; j<ret; ++j)
			{
				js_item = cJSON_CreateObject();
				cJSON_AddItemToObject(js_item, item_field_name[5], cJSON_CreateNumber(i));

				//dev_mac sensor_name
				for(k=0; k<2; ++k)
				{
					cJSON_AddItemToObject(js_item, item_field_name[k], cJSON_CreateString(sensor_dat[j][k]));
				}

				k=0;
				dat_result=0;
				while(sensor_dat[j][2][k]!='\0')
				{
					//printf("j=%d k=%d %c\n", j, k, sensor_dat[j][2][k]);
					dat_result = (dat_result*10)+(sensor_dat[j][2][k]-'0');
					++k;
				}
				//printf("dat_result=%d j=%d k=%d\n", dat_result, j, k);

				//sensor_status
				if(i==CMD_PSST||i==CMD_TEMPERATURE||i==CMD_HUMIDITY)
				{
					//整型数据
					cJSON_AddItemToObject(js_item, item_field_name[2], cJSON_CreateNumber(dat_result));
				}
				else
				{
					//bool数据
					if(dat_result!=0)
					{
						cJSON_AddTrueToObject(js_item, item_field_name[2]);
					}
					else
					{
						cJSON_AddFalseToObject(js_item, item_field_name[2]);
					}
				}
				//使用mac地址查找region
				res = sql_query_strfield_by_strfield(devcfg_table, item_field_name[3], dev_dat, item_field_name[0], sensor_dat[j][0]);
				cJSON_AddItemToObject(js_item, item_field_name[3], cJSON_CreateString(dev_dat));

				dat_result = sql_query_intfield_by_strfield(devcfg_table, item_field_name[4], item_field_name[0], sensor_dat[j][0]);
				if(dat_result == ZB_DEV_ONLINE)
				{
					cJSON_AddTrueToObject(js_item, item_field_name[4]);
				}
				else if(dat_result == ZB_DEV_OFFLINE)
				{
					cJSON_AddFalseToObject(js_item, item_field_name[4]);
				}

				cJSON_AddItemToArray(js_sensor_arry, js_item);
			}
		}
	}
	cJSON_AddItemToObject(js_root, json_root_name, js_sensor_arry);

	result = cJSON_Print(js_root);
	//printf("%s\n", result);
	strcpy(result_str, result);
	cJSON_Delete(js_root);
	free(result);

	return res;
}

/*********************************************************************
* @fn      add_alarm_task
*
* @brief   添加一个定时任务
*
* @param   dev_mac:设备mac地址
* @param   sensor_type:传感器类型
* @param   sensor_status:设置的传感器状态
* @param   alarm_time:定时时间 hour:min
* @param   alarm_repeat:表示闹钟是否重复
*
* @return  成功返回0 失败返回-1
*/
int add_alarm_task(char *alarm_name, char *dev_mac, char sensor_type, char sensor_status, char *alarm_time, char alarm_repeat, char alarm_status)
{
    int res=0;
    alarm_task_msg_pkg alarm_task_pkg;

	Sem_Init();
	Msg_queue_Init();

    alarm_task_pkg.msgtype      = MSG_QUEUE_ALARM_TYPE;
    alarm_task_pkg.type         = sensor_type;
    alarm_task_pkg.status       = sensor_status;
    alarm_task_pkg.alarm_repeat = alarm_repeat;
	alarm_task_pkg.alarm_status = alarm_status;
    strcpy(alarm_task_pkg.name, alarm_name);
    strcpy(alarm_task_pkg.mac, dev_mac);
    strcpy(alarm_task_pkg.alarm_time, alarm_time);

    poperation(sem_msg_queue_qt_id, g_sem_id);//消息队列读写锁
	res = msgsnd(g_msgid, (void *)&alarm_task_pkg, sizeof(alarm_task_pkg)-sizeof(long), 0);
	voperation(sem_msg_queue_qt_id, g_sem_id);
	voperation(sem_alarm_task_list, g_sem_id);

	return res;
}

/*********************************************************************
* @fn      delete_zb_node
*
* @brief   删除一个传感器节点
*
* @param   dev_mac:设备mac地址
*
* @return  成功返回0 失败返回-1
*/
int delete_zb_node(const char *dev_mac)
{
    long int i,type,res=-1;

    char *field[]={"dev_mac", "dev_type"};

    type = sql_query_intfield_by_strfield(devcfg_table, field[1], field[0], dev_mac);

    for(i=0; i<32; ++i)
    {
        if(type & (1<<i))
        {
            res = sql_delete_line(sensor_table[i], field[0], dev_mac, SQL_FIEL_TYPE_STR);
            if(res!=0)
            {
                break;
            }
        }
    }

    if(res==0)
    {
        res = sql_delete_line(devcfg_table, field[0], dev_mac, SQL_FIEL_TYPE_STR);
    }

    return res;
}

int send_alarm_task_info(char *result_str)
{
    /*  id 名称 mac地址 sensor_name 定时时间 重复 定时传感器状态 定时状态
        {"timing_list":{{"alarm_id":"", "timing_name":"", "dev_mac":"", "sensor_name":"",
                        "timing_time":"", "timing_freq":"", "timng_sensor_status":"", "timg_status":""},{},}}
    */
    int i,j,k,res=0,ret;
	int dat_result,sensor_type;
	char *result;
	char sql_dat[10][10][256];
	char res_dat[128];
	int col[]={0,1,2,3,4,5,6,7};
	char *json_root_name = "timing_list";
	char *item_field_name[]={"alarm_id", "timing_name", "dev_mac", "sensor_name", "timing_sensor_status", "timing_time", "timing_status", "timing_freq"};
	char col_type[]={SQL_FIEL_TYPE_INT, SQL_FIEL_TYPE_STR, SQL_FIEL_TYPE_STR, SQL_FIEL_TYPE_INT, SQL_FIEL_TYPE_INT, SQL_FIEL_TYPE_STR, SQL_FIEL_TYPE_INT, SQL_FIEL_TYPE_INT};
	cJSON *js_root,*js_sensor_arry,*js_item;

	js_root             = cJSON_CreateObject();
	js_sensor_arry      = cJSON_CreateArray();

	//获取整个定时表格的数据
	res = sql_get_table_nfield("alarm_task", col, col_type, 8, sql_dat);
	for(i=0; i<res; ++i)
    {
        js_item = cJSON_CreateObject();

        dat_result = str_to_int(sql_dat[i][0]);
        //alarm_id
        cJSON_AddItemToObject(js_item, item_field_name[0], cJSON_CreateNumber(dat_result));
        //timing_name
        cJSON_AddItemToObject(js_item, item_field_name[1], cJSON_CreateString(sql_dat[i][1]));
        //dev_mac
        cJSON_AddItemToObject(js_item, item_field_name[2], cJSON_CreateString(sql_dat[i][2]));
        //sensor_name sensor_type
        sensor_type = str_to_int(sql_dat[i][3]);//sensor_type
        ret = sql_query_strfield_by_strfield(sensor_table[sensor_type], "sensor_name", res_dat, "dev_mac", sql_dat[i][2]);
        cJSON_AddItemToObject(js_item, item_field_name[3], cJSON_CreateString(res_dat));
        //timng_sensor_status
        dat_result = str_to_int(sql_dat[i][4]);
        if(sensor_type==CMD_LIGHT||sensor_type==CMD_RELAY||sensor_type==CMD_CALORIFIER||sensor_type==CMD_CURTAIN)
        {
            // on-0 off-1
            if(dat_result==0)
            {
                cJSON_AddTrueToObject(js_item, item_field_name[4]);
            }
            else
            {
                cJSON_AddFalseToObject(js_item, item_field_name[4]);
            }
        }
        else
        {
            // on-1 off-0
            if(dat_result==1)
            {
                cJSON_AddTrueToObject(js_item, item_field_name[4]);
            }
            else
            {
                cJSON_AddFalseToObject(js_item, item_field_name[4]);
            }
        }
        //timing_time
        cJSON_AddItemToObject(js_item, item_field_name[5], cJSON_CreateString(sql_dat[i][5]));
        //timg_status
        dat_result = str_to_int(sql_dat[i][6]);
        if(dat_result==1)
        {
            cJSON_AddTrueToObject(js_item, item_field_name[6]);
        }
        else
        {
            cJSON_AddFalseToObject(js_item, item_field_name[6]);
        }
        //timing_freq
        dat_result = str_to_int(sql_dat[i][7]);
        if(dat_result==1)
        {
            cJSON_AddTrueToObject(js_item, item_field_name[7]);
        }
        else
        {
            cJSON_AddFalseToObject(js_item, item_field_name[7]);
        }
        cJSON_AddItemToArray(js_sensor_arry, js_item);
    }
    cJSON_AddItemToObject(js_root, json_root_name, js_sensor_arry);

    result = cJSON_Print(js_root);
	//printf("%s\n", result);
	strcpy(result_str, result);
	cJSON_Delete(js_root);
	free(result);

    if(res!=-1)
    {
        res=0;
    }

    return res;
}

/*********************************************************************
* @fn      delete_timing_node
*
* @brief   删除一个定时任务
*
* @param   alarm_task_id:定时任务id
*
* @return  成功返回0 失败返回-1
*/
int delete_timing_node(int alarm_task_id)
{
    int res=0;
    char id_array[8];
    del_alarm_task_msg del_alarm_task_pkg;

	Sem_Init();
	Msg_queue_Init();

    sprintf(id_array, "%d", alarm_task_id);
    res = sql_delete_line("alarm_task", "ID", id_array, SQL_FIEL_TYPE_INT);

    //printf("id:%d res=%d\n", alarm_task_id, res);
    if(res==0)
    {
        del_alarm_task_pkg.msgtype           = MSG_QUEUE_DEL_ALARM_TYPE;
        del_alarm_task_pkg.del_alarm_task_id = alarm_task_id;

        poperation(sem_msg_queue_qt_id, g_sem_id);//消息队列读写锁
        res = msgsnd(g_msgid, (void *)&del_alarm_task_pkg, sizeof(del_alarm_task_msg)-sizeof(long), 0);
        voperation(sem_msg_queue_qt_id, g_sem_id);
        voperation(sem_del_alarm_task, g_sem_id);
    }

    return res;
}

/*********************************************************************
* @fn      update_alarm_task
*
* @brief   更新定时列表
*
* @param   alarm_id:定时任务id
* @param   field_value:五个字段的值
*
* @return  成功返回0 失败返回-1
*/
int update_alarm_task(const int alarm_id, char field_value[][128])
{
    int res=0,i,sensor_type,sensor_status;
    char id_value[8];
    char *location_field="ID";
    char *field_list[]={"alarm_name", "sensor_status", "alarm_time", "alarm_switch", "alarm_repeat"};
    char field_type[]={SQL_FIEL_TYPE_STR, SQL_FIEL_TYPE_INT, SQL_FIEL_TYPE_STR, SQL_FIEL_TYPE_INT, SQL_FIEL_TYPE_INT};

    sprintf(id_value, "%d", alarm_id);
	sensor_type   = sql_query_value_by_id("alarm_task", "sensor_type", alarm_id);
	sensor_status = str_to_int(field_value[1]);

	if(sensor_type==CMD_LIGHT||sensor_type==CMD_RELAY||sensor_type==CMD_CALORIFIER||sensor_type==CMD_CURTAIN)
	{
		//on-0 off-1
		sensor_status = sensor_status==0?1:0;
		sprintf(field_value[1], "%d", sensor_status);
	}

    for(i=0; i<5; ++i)
    {
        res = update_field_value("alarm_task", field_list[i], field_value[i], field_type[i], "ID", id_value, SQL_FIEL_TYPE_INT);
        if(res!=0)
        {
            break;
        }
    }
	
	voperation(sem_update_alarm_task, g_sem_id);

    return res;
}

/*********************************************************************
* @fn      insert_emergency_call_number
*
* @brief   添加一个紧急联系号码
*
* @param   number:电话号码
*
* @return  成功返回0 失败返回-1
*/
int insert_emergency_call_number(const char *number)
{
	int res=0;
	char dat_buf[2][32];
	char *emergency_call_table = "emergency_call_number";
	int type[] = {SQL_FIEL_TYPE_INT, SQL_FIEL_TYPE_STR};

    if(strlen(number)!=11)
        return -1;

	sprintf(dat_buf[0], "%s", "NULL");
	sprintf(dat_buf[1], "%s", number);

	Sem_Init();
	Msg_queue_Init();

	res = insert_line_data(emergency_call_table, dat_buf, type, 2);

	return res;
}

/*********************************************************************
* @fn      updata_emergency_call_number
*
* @brief   更新紧急电话号码
*
* @param   id:号码id
* @param   number:电话号码
*
* @return  成功返回0 失败返回-1
*/
int updata_emergency_call_number(const int id, const char *number)
{
	int res=0;
	char *emergency_call_table = "emergency_call_number";
	char *field_name[]={"ID", "phone_number"};
	int type[]={SQL_FIEL_TYPE_INT, SQL_FIEL_TYPE_STR};
	char id_value[8];

	Sem_Init();
	Msg_queue_Init();

	sprintf(id_value, "%d", id);
	res = update_field_value(emergency_call_table, field_name[1], number, type[1], field_name[0], id_value, type[0]);

	return res;
}

/*********************************************************************
* @fn      del_emergency_call_number
*
* @brief   删除紧急电话号码
*
* @param   id:号码id
*
* @return  成功返回0 失败返回-1
*/
int del_emergency_call_number(const int id)
{
	int res=0;
	char *emergency_call_table = "emergency_call_number";
	char id_value[8];

	Sem_Init();
	Msg_queue_Init();

	sprintf(id_value, "%d", id);
	res = sql_delete_line(emergency_call_table, "ID", id_value, SQL_FIEL_TYPE_INT);

	return res;
}

/*********************************************************************
* @fn      get_emergency_call_number
*
* @brief   得到紧急电话表
*
* @param   result:json格栅管结果
*
* @return  成功返回0 失败返回-1
*/
int get_emergency_call_number(char *result_str)
{
	int i,j,k,res=0,ret,num;
	int dat_result;
	char *result;
	char emergency_dat[10][10][256];
	int col[]={0,1};
	char *emergency_call_table = "emergency_call_number";
	char *json_root_name = "emergency_call_number";
	char *item_field_name[]={"ID", "phone_number"};
	char col_type[]={SQL_FIEL_TYPE_INT, SQL_FIEL_TYPE_STR};
	cJSON *js_root,*js_sensor_arry,*js_item;

	num            = sql_get_table_nfield(emergency_call_table, col, col_type, 2, emergency_dat);
	js_root        = cJSON_CreateObject();
	js_sensor_arry = cJSON_CreateArray();

	if(num==-1)
        res = num;

	for(i=0; i<num; ++i)
	{
		js_item    = cJSON_CreateObject();
		dat_result = str_to_int(emergency_dat[i][0]);

		//ID
		cJSON_AddItemToObject(js_item, item_field_name[0], cJSON_CreateNumber(dat_result));
		//number
		cJSON_AddItemToObject(js_item, item_field_name[1], cJSON_CreateString(emergency_dat[i][1]));

		cJSON_AddItemToArray(js_sensor_arry, js_item);
	}
	cJSON_AddItemToObject(js_root, json_root_name, js_sensor_arry);

	result = cJSON_Print(js_root);
	//printf("%s\n", result);
	strcpy(result_str, result);
	cJSON_Delete(js_root);
	free(result);

	return res;
}
